package com.hu.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hu.reggie.common.CustomException;
import com.hu.reggie.dto.SetmealDto;
import com.hu.reggie.mapper.SetmealMapper;
import com.hu.reggie.pojo.Setmeal;
import com.hu.reggie.pojo.SetmealDish;
import com.hu.reggie.service.SetmealDishService;
import com.hu.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;

    // 新增套餐，并保存菜品和套餐关联关系
    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        // 保存套餐信息
        this.save(setmealDto);
        // 保存套餐和菜品的关联关系
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.stream().map(item ->{
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());

        setmealDishService.saveBatch(setmealDishes);
    }

    // 删除套餐，同时删除菜品和套餐的关联关系
    @Override
    public void deleteWithDish(List<Long> ids) {
        // 查询套餐状态，确定是否可以删除
        LambdaQueryWrapper<Setmeal> queryWrapper=new LambdaQueryWrapper<>();
        // 停售则删除
        // 添加条件，id in ids，status=1
        queryWrapper.in(Setmeal::getId,ids);
        queryWrapper.eq(Setmeal::getStatus,1);
        int count = this.count(queryWrapper);
        // 结果大于0说明有正在出售的套餐
        if(count >0){
            throw new CustomException("套餐正在出售，不能删除");
        }else {
            this.removeByIds(ids);
        }

        // 删除关系表
        LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(SetmealDish::getDishId,ids);
        setmealDishService.remove(lambdaQueryWrapper);
    }
}
